import axios from 'axios'
import qs from 'qs'
import store from "@/store";

// 生成Axios的伪实例
const instance = axios.create({
    baseURL: 'http://127.0.0.1:50101/'
})

// 请求拦截器
instance.interceptors.request.use(config => {
    const token = sessionStorage.getItem("token")
    if (!!token) {
        config.headers = {
            'Authorization': token
        }
    }
    switch (config.headers['Content-Type']) {
        case 'application/x-www-form-urlencoded':
            config.data = qs.stringify(config.data)
            break;
        default:
            break;
    }
    return config;
})


// 响应拦截器
instance.interceptors.response.use(
    response => {
        if (response.data.data) {
            if (response.data.data.token) {
                sessionStorage.setItem("token",response.data.data.token)
                store.commit('token', response.data.data.token);
                sessionStorage.setItem("userInfo",JSON.stringify(response.data.data.userInfo))
                if (response.data.data.userInfo) {
                    store.commit('userInfo', JSON.stringify(response.data.data.userInfo));
                }
            }
        }
        // console.log(response)
        return response.data;
    },
    error => {
        // console.error(error)
        return Promise.reject(error);
    }
)

export default instance
